var BackofficeAdsManage = {
	
	load : function () {
	 	
		Ext.getDom("userName").innerHTML =  getUser().Name;	
		new Ext.form.DateField({       
		      applyTo : 'startDate',
		      format: 'Y/m/d',       
		      emptyText: '' 
		});       
		
		new Ext.form.DateField({       
		      applyTo : 'endDate',       
		      format: 'Y/m/d',
		      emptyText: ''        
		}); 
		
		this.eventRegister();
		this.queryData();	
	},
	
	eventRegister : function (){ 		
		Ext.get("btnQuery").on("click",this.query); //檢查使用者帳號
	},
	
	openAdDetail : function (adId) {
		var url = "/ad/html/backoffice/AdDetail.php?adId=" + adId
		var width =800;
		var  height = 550;	
		window.showModalDialog(url,null,'dialogHeight:'+height+'pt;dialogWidth:'+800+'pt;center:yes;status=no');
		
		BackofficeAdsManage.store.reload();
	},
	
	query : function () {
	   var params = {
	    	  proxyName　: Ext.getDom("proxyName").value,
			  name : Ext.getDom("name").value,
			  startDate : Ext.getDom("startDate").value,
			  endDate : Ext.getDom("endDate").value,
			  status : getRedioValue("status"),
			  start : 0,
			  limit : 10 
	   };
	   
	   if (params.startDate != "" && !params.startDate.isDate()) {
	   	   alert("請輸入 開始日期 格式錯誤!");
	       return;
	   }
	   
	   if (params.endDate != "" && !params.endDate.isDate()) {
	   	   alert("請輸入 結束日期 格式錯誤!");
	       return;
	   }
	   	     
	   if (params.startDate == "" && params.endDate != "") {
	       alert("請輸入 查詢開始日期!");
	    	return;
	   }
	    
	   if (params.startDate != "" && params.endDate == "") {
	        alert("請輸入 查詢結束日期!");
	    	return;
	   }
	    
	   
	   
	   if (params.startDate != "" && params.endDate != "" && params.startDate >   params.endDate) {
	    	alert("查詢日期格式錯誤!");
	    	return;
	   }
		 
	     BackofficeAdsManage.store.addListener({
			beforeload:function(store,records,options){
				store.baseParams =  params;			
			}
		}); 
	   
	   BackofficeAdsManage.store.load({params: params});
	},
	
	queryData : function () {
		var params = {
			  proxyName　: Ext.getDom("proxyName").value,
			  name : Ext.getDom("name").value,
			  startDate : Ext.getDom("startDate").value,
			  endDate : Ext.getDom("endDate").value,
			  status : getRedioValue("status"),
			  start:0, 
			  limit:10  
		};
		
		/*
		 var store = new Ext.ux.data.PagingStore({
	        proxy :"/ad/sys/com/control/AdService.php?action=managerAd",
	        reader: new Ext.data.JsonReader({
	            root : "row",
	            totalProperty: 'count',
	            fields : ["id","adName", "status", "proxyName", "name","sumBudget","actualImpressions","actuaClick", "createTime","isPay","point", "adStartDate", "adEndDate"]
	        })
	    });*/
		
		BackofficeAdsManage.store = new Ext.data.JsonStore ({
	 	 	url:"/ad/sys/com/control/AdService.php?action=managerAd",
			root : "row",
			method : "post",
			 baseParams :  params,
			totalProperty: 'count',
			fields : ["id","adName", "status", "proxyName", "name","sumBudget","actualImpressions","actuaClick", "createTime","isPay","point", "adStartDate", "adEndDate"]
		});
	 
		BackofficeAdsManage.grid =new Ext.grid.GridPanel({
			renderTo : "grid",
			store :  BackofficeAdsManage.store,
			height: 340,
			loadMask : true,
			viewConfig : {
				forceFit : true 
			},
			columns : [ 
				new Ext.grid.RowNumberer(),
				{header : "名稱" ,dataIndex : "adName", width :60,sortable : true,
					renderer: function (v,p,r) {
						 return String.format("<a href=javascript:BackofficeAdsManage.openAdDetail({0})>{1}</a>"  , r.data.id , v);;   	
					}
				},
				{header : "狀態", dataIndex : "status" , width : 30, sortable : true,
					renderer : function (value, p , r) {
						//廣告狀態 0.審理中 1.刊登中 2.已結束,3 暫停 4.刪除
						var statusText = "";
						switch(value) {
							case "0" : statusText = "審理中"; break;
							case "1" : statusText = "刊登中"; break;
							case "2" : statusText = "已結束"; break;
							case "3" : statusText = "暫停"; break;
							case "4" : statusText = "刪除"; break;
							case "5" : statusText = "未通過"; break;
							case "6" : statusText = "需修改"; break;
						}
						
						/*
						if (value == "0") {
							return String.format("<a href=javascript:BackofficeAdsManage.openAdDetail({0})>{1}</a>"  ,r.data.id , statusText);
						} else {
							return statusText;
						}*/
						return statusText;						 
					}
				},
				{header : "媒體代理商", dataIndex : "proxyName",width :30, sortable : true},
				{header : "客戶名稱", dataIndex : "name",width :30,sortable : true},
				{header : "總預算", dataIndex : "sumBudget",width :30 , sortable : true, 
					renderer: function (v,p,r) {
						 return String.format("<a href=javascript:BackofficeAdsManage.openDialog({0})>{1}</a>"  ,r.id , v);;   	
					}
				}, 
				{header : "曝光", width : 40, dataIndex : "actualImpressions",width :30 , sortable : true},
				{header : "點擊", width : 40, dataIndex : "actuaClick",width :30 , sortable : true,
					renderer: function (v,p,r) {
						return v;   	
					}
				}, 
				{header : "", width : 40, renderer: function (v,p,r) {
					return String.format('<input type="button"  class="gridBtn" value="編輯" onclick="BackofficeAdsManage.toEdit({0})"/>',r.data.id);   	
				}}
				
			],
			
			bbar : new Ext.PagingToolbar({
				pageSize :10,
				store : BackofficeAdsManage.store,
				displayInfo : true,
				displayMsg : "顯示第 {0} 筆到 {1} 筆紀錄,共 {2} 筆紀錄",
				emptyMsg : "沒有紀錄"/*,
				doLoad: function(v){
					var start = (this.cursor +1) * 10;
					var limit = (this.cursor + 2) * 10;
				 
					if (this.fireEvent("beforechange", this, params) !== false) {
						this.store.load({
							  proxyName　: Ext.getDom("proxyName").value,
							  name : Ext.getDom("name").value,
							  startDate : Ext.getDom("startDate").value,
							  endDate : Ext.getDom("endDate").value,
							  status : getRedioValue("status"),
			 	  			  start : start,
							  limit : limit
						}); 
					}
				}*/
				
			}) 
		});	
		
		BackofficeAdsManage.store.load({params:params});    
	}, 
	
	toEdit : function (adId) {
		location.href="/ad/sys/com/control/AdService.php?action=managerStep1Action&adId=" + adId;
	},
	
	openDialog : function (id){
		var data = BackofficeAdsManage.store.getById(id).data;
		
		Ext.getDom("detailAdName").innerHTML = data.adName;
		Ext.getDom("detailStartDate").innerHTML = data.adStartDate;
		Ext.getDom("detailEndDate").innerHTML = data.adEndDate;
		
		Ext.getDom("detailSumBudget").innerHTML = data.sumBudget;
		Ext.getDom("detailCreateTime").innerHTML = data.createTime.toDateString();
	    Ext.getDom("detailPoint").innerHTML = data.point;
		document.getElementsByName("isPay")[data.isPay ==0 ? 1 : 0].checked = true;
	  
	    
		$( "#dialog-confirm" ).dialog({
			resizable:true,
			minWidth: 500,
			minHeight:450,
			modal: true,
			buttons: {
				"確認": function() {
					var dialog = this;
					var tempIsPay = getRedioValue("isPay");
					
					if (tempIsPay != data.isPay) {
						Ext.Ajax.request({
							url : "/ad/sys/com/control/AdService.php?action=updateAdPay&adId=" + data.id +"&isPay=" + tempIsPay,
							callback : function (options, success, rsp) {
								var obj =  rsp.responseText.toJSON();  
								 
								if (obj.result > 0) {
									alert("修改成功!");
								}  else {
									alert("修改失敗!");
								}
								BackofficeAdsManage.store.reload();
								$( dialog ).dialog( "close" );
							} 
						});
					} else {
						$( this ).dialog( "close" );
					}
				},
				"取消": function() {
					$( this ).dialog( "close" );
				}
			}
		});	
	}
}


Ext.onReady(function (){
	BackofficeAdsManage.load();
});